import React, { useState, useEffect } from 'react';
import './AuditLogPage.css';
import Breadcrumb from '../../components/Breadcrumb';

// 审计日志类型定义
interface AuditLog {
  id: string;
  timestamp: string;
  user: string;
  userId: string;
  action: string;
  module: string;
  details: string;
  ipAddress: string;
  status: 'success' | 'failed' | 'warning';
}

// 日志状态选项
const statusOptions = [
  { value: 'all', label: '全部状态' },
  { value: 'success', label: '成功' },
  { value: 'failed', label: '失败' },
  { value: 'warning', label: '警告' },
];

// 模块选项
const moduleOptions = [
  { value: 'all', label: '全部模块' },
  { value: 'system', label: '系统管理' },
  { value: 'user', label: '用户管理' },
  { value: 'student', label: '学生管理' },
  { value: 'teacher', label: '教师管理' },
  { value: 'class', label: '班级管理' },
  { value: 'attendance', label: '考勤管理' },
  { value: 'grades', label: '成绩管理' },
];

// 操作类型选项
const actionOptions = [
  { value: 'all', label: '全部操作' },
  { value: 'login', label: '登录' },
  { value: 'logout', label: '登出' },
  { value: 'create', label: '创建' },
  { value: 'update', label: '更新' },
  { value: 'delete', label: '删除' },
  { value: 'view', label: '查看' },
  { value: 'import', label: '导入' },
  { value: 'export', label: '导出' },
  { value: 'settings', label: '设置' },
];

// 生成模拟审计日志数据
const generateMockAuditLogs = (): AuditLog[] => {
  const logs: AuditLog[] = [];
  const actions = ['login', 'logout', 'create', 'update', 'delete', 'view', 'import', 'export', 'settings'];
  const modules = ['system', 'user', 'student', 'teacher', 'class', 'attendance', 'grades'];
  const users = [
    { id: 'admin001', name: '管理员' },
    { id: 'teacher001', name: '张老师' },
    { id: 'teacher002', name: '李老师' },
    { id: 'admin002', name: '系统管理员' },
    { id: 'teacher003', name: '王老师' },
  ];
  const statuses: Array<'success' | 'failed' | 'warning'> = ['success', 'failed', 'warning'];
  const ipRanges = ['192.168.1.', '10.0.0.', '172.16.0.'];

  // 生成最近30天的模拟数据，每天约50条记录
  for (let i = 0; i < 1500; i++) {
    const date = new Date();
    date.setDate(date.getDate() - Math.floor(Math.random() * 30));
    date.setHours(Math.floor(Math.random() * 24));
    date.setMinutes(Math.floor(Math.random() * 60));
    date.setSeconds(Math.floor(Math.random() * 60));
    
    const action = actions[Math.floor(Math.random() * actions.length)];
    const module = modules[Math.floor(Math.random() * modules.length)];
    const user = users[Math.floor(Math.random() * users.length)];
    const status = statuses[Math.floor(Math.random() * statuses.length)];
    const ipAddress = `${ipRanges[Math.floor(Math.random() * ipRanges.length)]}${Math.floor(Math.random() * 255)}`;
    
    // 根据操作类型生成详细信息
    let details = '';
    switch (action) {
      case 'login':
        details = status === 'success' ? '用户登录成功' : '登录失败：密码错误';
        break;
      case 'logout':
        details = '用户主动登出系统';
        break;
      case 'create':
        details = `创建了新的${getModuleName(module)}记录`;
        break;
      case 'update':
        details = `更新了${getModuleName(module)}的信息`;
        break;
      case 'delete':
        details = `删除了${getModuleName(module)}的记录`;
        break;
      case 'view':
        details = `查看了${getModuleName(module)}的信息`;
        break;
      case 'import':
        details = `导入了${getModuleName(module)}数据`;
        break;
      case 'export':
        details = `导出了${getModuleName(module)}数据`;
        break;
      case 'settings':
        details = '修改了系统设置';
        break;
    }
    
    logs.push({
      id: `log-${Date.now()}-${i}`,
      timestamp: date.toISOString(),
      user: user.name,
      userId: user.id,
      action,
      module,
      details,
      ipAddress,
      status,
    });
  }
  
  // 按时间倒序排序
  return logs.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
};

// 获取模块中文名
const getModuleName = (module: string): string => {
  const moduleMap: { [key: string]: string } = {
    system: '系统',
    user: '用户',
    student: '学生',
    teacher: '教师',
    class: '班级',
    attendance: '考勤',
    grades: '成绩',
  };
  return moduleMap[module] || module;
};

// 获取操作中文名
const getActionName = (action: string): string => {
  const actionMap: { [key: string]: string } = {
    login: '登录',
    logout: '登出',
    create: '创建',
    update: '更新',
    delete: '删除',
    view: '查看',
    import: '导入',
    export: '导出',
    settings: '设置',
  };
  return actionMap[action] || action;
};

const AuditLogPage: React.FC = () => {
  const [logs, setLogs] = useState<AuditLog[]>([]);
  const [filteredLogs, setFilteredLogs] = useState<AuditLog[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [moduleFilter, setModuleFilter] = useState('all');
  const [actionFilter, setActionFilter] = useState('all');
  const [dateRange, setDateRange] = useState<{ start: string; end: string }>({
    start: '',
    end: '',
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [totalPages, setTotalPages] = useState(1);

  // 加载审计日志数据
  useEffect(() => {
    const loadAuditLogs = () => {
      setLoading(true);
      try {
        // 尝试从localStorage加载数据
        const storedLogs = localStorage.getItem('auditLogs');
        if (storedLogs) {
          setLogs(JSON.parse(storedLogs));
        } else {
          // 如果没有存储的数据，生成模拟数据
          const mockLogs = generateMockAuditLogs();
          localStorage.setItem('auditLogs', JSON.stringify(mockLogs));
          setLogs(mockLogs);
        }
      } catch (error) {
        console.error('加载审计日志失败:', error);
        // 如果出错，生成一些基本的模拟数据
        const fallbackLogs = generateMockAuditLogs().slice(0, 100);
        setLogs(fallbackLogs);
      } finally {
        setLoading(false);
      }
    };

    loadAuditLogs();
  }, []);

  // 筛选和分页处理
  useEffect(() => {
    // 筛选日志
    let result = [...logs];
    
    // 搜索查询筛选
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      result = result.filter(log => 
        log.user.toLowerCase().includes(query) ||
        log.userId.toLowerCase().includes(query) ||
        log.details.toLowerCase().includes(query) ||
        log.ipAddress.includes(query)
      );
    }
    
    // 状态筛选
    if (statusFilter !== 'all') {
      result = result.filter(log => log.status === statusFilter);
    }
    
    // 模块筛选
    if (moduleFilter !== 'all') {
      result = result.filter(log => log.module === moduleFilter);
    }
    
    // 操作筛选
    if (actionFilter !== 'all') {
      result = result.filter(log => log.action === actionFilter);
    }
    
    // 日期范围筛选
    if (dateRange.start && dateRange.end) {
      const startDate = new Date(dateRange.start);
      const endDate = new Date(dateRange.end);
      endDate.setHours(23, 59, 59, 999); // 设置为当天的最后一刻
      
      result = result.filter(log => {
        const logDate = new Date(log.timestamp);
        return logDate >= startDate && logDate <= endDate;
      });
    }
    
    // 计算总页数
    const total = Math.ceil(result.length / pageSize);
    setTotalPages(total);
    
    // 确保当前页码在有效范围内
    if (currentPage > total && total > 0) {
      setCurrentPage(total);
    }
    
    // 分页处理
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    setFilteredLogs(result.slice(startIndex, endIndex));
  }, [logs, searchQuery, statusFilter, moduleFilter, actionFilter, dateRange, currentPage, pageSize]);

  // 处理日期范围变化
  const handleDateRangeChange = (field: 'start' | 'end', value: string) => {
    setDateRange(prev => ({ ...prev, [field]: value }));
    setCurrentPage(1); // 重置到第一页
  };

  // 处理搜索提交
  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setCurrentPage(1); // 重置到第一页
  };

  // 清除所有筛选条件
  const handleClearFilters = () => {
    setSearchQuery('');
    setStatusFilter('all');
    setModuleFilter('all');
    setActionFilter('all');
    setDateRange({ start: '', end: '' });
    setCurrentPage(1);
  };

  // 导出审计日志
  const handleExportLogs = () => {
    try {
      const dataToExport = filteredLogs.map(log => ({
        '时间': new Date(log.timestamp).toLocaleString(),
        '用户': log.user,
        '用户ID': log.userId,
        '操作': getActionName(log.action),
        '模块': getModuleName(log.module),
        '详情': log.details,
        'IP地址': log.ipAddress,
        '状态': log.status === 'success' ? '成功' : log.status === 'failed' ? '失败' : '警告',
      }));
      
      const csvContent = [
        Object.keys(dataToExport[0]).join(','), // 表头
        ...dataToExport.map(row => Object.values(row).join(',')) // 数据行
      ].join('\n');
      
      const blob = new Blob([`\ufeff${csvContent}`], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', `audit_logs_${new Date().toISOString().split('T')[0]}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      console.error('导出日志失败:', error);
      alert('导出日志失败，请稍后重试');
    }
  };

  // 渲染状态标签
  const renderStatusTag = (status: string) => {
    const statusClasses = {
      success: 'status-success',
      failed: 'status-failed',
      warning: 'status-warning',
    };
    
    const statusLabels = {
      success: '成功',
      failed: '失败',
      warning: '警告',
    };
    
    return (
      <span className={`status-tag ${statusClasses[status as keyof typeof statusClasses]}`}>
        {statusLabels[status as keyof typeof statusLabels]}
      </span>
    );
  };

  if (loading) {
    return (
      <div className="audit-log-page">
        <div className="loading-container">加载审计日志中...</div>
      </div>
    );
  }

  return (
    <div className="audit-log-page">
      <div className="page-header">
        <h1>审计日志</h1>
        <Breadcrumb
          items={[
            { id: 'dashboard', title: '首页' },
            { id: 'audit', title: '审计日志' }
          ]}
          activeItemId="audit"
        />
      </div>

      {/* 搜索和筛选区域 */}
      <div className="filter-section">
        <form className="filter-form" onSubmit={handleSearchSubmit}>
          <div className="filter-row">
            <div className="filter-item">
              <label htmlFor="search">搜索</label>
              <input
                type="text"
                id="search"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="搜索用户、ID、详情或IP地址"
                className="filter-input"
              />
            </div>
            
            <div className="filter-item">
              <label htmlFor="status">状态</label>
              <select
                id="status"
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
                className="filter-select"
              >
                {statusOptions.map(option => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>

            <div className="filter-item">
              <label htmlFor="module">模块</label>
              <select
                id="module"
                value={moduleFilter}
                onChange={(e) => setModuleFilter(e.target.value)}
                className="filter-select"
              >
                {moduleOptions.map(option => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>

            <div className="filter-item">
              <label htmlFor="action">操作</label>
              <select
                id="action"
                value={actionFilter}
                onChange={(e) => setActionFilter(e.target.value)}
                className="filter-select"
              >
                {actionOptions.map(option => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>
          </div>

          <div className="filter-row">
            <div className="filter-item">
              <label htmlFor="start-date">开始日期</label>
              <input
                type="date"
                id="start-date"
                value={dateRange.start}
                onChange={(e) => handleDateRangeChange('start', e.target.value)}
                className="filter-input"
              />
            </div>

            <div className="filter-item">
              <label htmlFor="end-date">结束日期</label>
              <input
                type="date"
                id="end-date"
                value={dateRange.end}
                onChange={(e) => handleDateRangeChange('end', e.target.value)}
                className="filter-input"
              />
            </div>

            <div className="filter-actions">
              <button type="submit" className="btn-search">搜索</button>
              <button type="button" className="btn-clear" onClick={handleClearFilters}>
                清除筛选
              </button>
              <button type="button" className="btn-export" onClick={handleExportLogs}>
                导出日志
              </button>
            </div>
          </div>
        </form>
      </div>

      {/* 日志列表 */}
      <div className="logs-container">
        <div className="logs-header">
          <h2>审计日志记录</h2>
          <div className="log-stats">
            <span>共 {logs.length} 条记录，已筛选 {filteredLogs.length} 条</span>
          </div>
        </div>

        <div className="logs-table-container">
          <table className="logs-table">
            <thead>
              <tr>
                <th>时间</th>
                <th>用户</th>
                <th>用户ID</th>
                <th>操作</th>
                <th>模块</th>
                <th>详情</th>
                <th>IP地址</th>
                <th>状态</th>
              </tr>
            </thead>
            <tbody>
              {filteredLogs.length > 0 ? (
                filteredLogs.map(log => (
                  <tr key={log.id}>
                    <td>{new Date(log.timestamp).toLocaleString()}</td>
                    <td>{log.user}</td>
                    <td>{log.userId}</td>
                    <td>{getActionName(log.action)}</td>
                    <td>{getModuleName(log.module)}</td>
                    <td>{log.details}</td>
                    <td>{log.ipAddress}</td>
                    <td>{renderStatusTag(log.status)}</td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={8} className="no-data">
                    没有找到符合条件的审计日志记录
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* 分页控制 */}
        <div className="pagination">
          <div className="page-info">
            第 {currentPage} 页，共 {totalPages} 页
          </div>
          <div className="page-controls">
            <select
              value={pageSize}
              onChange={(e) => {
                setPageSize(Number(e.target.value));
                setCurrentPage(1);
              }}
              className="page-size-select"
            >
              <option value={10}>10条/页</option>
              <option value={20}>20条/页</option>
              <option value={50}>50条/页</option>
              <option value={100}>100条/页</option>
            </select>
            
            <button
              className="page-btn"
              onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
              disabled={currentPage === 1}
            >
              上一页
            </button>
            
            {/* 页码显示 */}
            <div className="page-numbers">
              {Array.from({ length: Math.min(5, totalPages) }, (_, index) => {
                let pageNum;
                if (totalPages <= 5) {
                  pageNum = index + 1;
                } else if (currentPage <= 3) {
                  pageNum = index + 1;
                } else if (currentPage >= totalPages - 2) {
                  pageNum = totalPages - 4 + index;
                } else {
                  pageNum = currentPage - 2 + index;
                }
                
                return (
                  <button
                    key={pageNum}
                    className={`page-btn ${currentPage === pageNum ? 'active' : ''}`}
                    onClick={() => setCurrentPage(pageNum)}
                  >
                    {pageNum}
                  </button>
                );
              })}
            </div>
            
            <button
              className="page-btn"
              onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
              disabled={currentPage === totalPages}
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AuditLogPage;